from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography import x509
from cryptography.x509.oid import NameOID
import os

profile = os.getenv("PROFILE", "/opt/datadir")
print(f"路径: {profile}") 
csr_path = profile + "/csr" 
# 生成密钥对
client_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)

# 保存私钥
with open(csr_path + '/client_private.key', 'wb') as f:
    f.write(client_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    ))

# 创建CSR
csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
    x509.NameAttribute(NameOID.COUNTRY_NAME, "CN"),
    x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Beijing"),
    x509.NameAttribute(NameOID.LOCALITY_NAME, "Beijing"),
    x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Taiji"),
    x509.NameAttribute(NameOID.COMMON_NAME, "taiji.com.cn"),
])).add_extension(
    x509.SubjectAlternativeName([
        x509.DNSName("taiji.com.cn"),
        x509.DNSName("www.taiji.com.cn")
    ]),
    critical=False,
).sign(client_key, hashes.SHA256())

# 将CSR转为PEM字符串并保存
csr_pem = csr.public_bytes(serialization.Encoding.PEM).decode('utf-8')
with open(csr_path + '/client_csr.csr', 'w') as f:
    f.write(csr_pem)

print("✅ 私钥已保存至: client_private.key")
print("✅ CSR文件已保存至: client_csr.csr")